package com.rzico.sbl.ui.report.driver

import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityDriverStationBarrelBinding
import com.rzico.sbl.model.DriverBarrel
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.DriverViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class DriverStationBarrelActivity : BaseActivity(R.layout.activity_driver_station_barrel) {

    private val mBinding by lazy { ActivityDriverStationBarrelBinding.bind(getRootView()) }

    override fun getViewModel() = get<DriverViewModel>()

    private val mBrandList = ArrayList<FilterData>()
    private lateinit var mDateMode: String
    private lateinit var mBeginDate: String
    private lateinit var mEndDate: String
    private var mBarrelId = ""

    override fun initData() {
        initTitle(title = "回桶统计")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关回桶记录！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            if (!isLoadingMore) {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                        }
                    )

                    view.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<DriverBarrel>(R.layout.item_report_station_barrel) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_barrel_time, bean.createDate.getTimeString())
                                text(R.id.item_barrel_hint, bean.name)
                                text(R.id.item_barrel_out, bean.quantity.orEmpty("0"))
                                text(R.id.item_barrel_in, bean.returnQuantity.orEmpty("0"))
                                text(R.id.item_barrel_qian, bean.arrearsQuantity.orEmpty("0"))
                                text(R.id.item_barrel_huan, bean.repayQuantity.orEmpty("0"))
                                text(R.id.item_barrel_driver, bean.backQuantity.orEmpty("0"))
                                text(R.id.item_barrel_old, bean.borrow.orEmpty("0"))
                                text(
                                    R.id.item_barrel_lei,
                                    (bean.borrow.intValue
                                            + bean.backQuantity.intValue
                                            + bean.arrearsQuantity.intValue
                                            - bean.repayQuantity.intValue).toString()
                                )

                                clicked {
                                    goToOrderDetail("orderSn" to bean.sn)
                                }
                            }
                        }
                        .attachTo(view)
                }
            }
    }

    override fun initListener() {
        mDateMode = intent.getExtra("dateMode")
        mBeginDate = intent.getExtra("beginDate")
        mEndDate = intent.getExtra("endDate")

        mBinding.apply {
            // 今日、昨日、本周、本月、上月、本年、自定义
            when (mDateMode) {
                "2" -> {
                    barrelTime.text = "昨日"
                    getViewModel().mUncheckTimeList[1].isChecked = true
                }
                "3" -> {
                    barrelTime.text = "本周"
                    getViewModel().mUncheckTimeList[2].isChecked = true
                }
                "4" -> {
                    barrelTime.text = "本月"
                    getViewModel().mUncheckTimeList[3].isChecked = true
                }
                "5" -> {
                    barrelTime.text = "上月"
                    getViewModel().mUncheckTimeList[4].isChecked = true
                }
                "6" -> {
                    barrelTime.text = "本年"
                    getViewModel().mUncheckTimeList[5].isChecked = true
                }
                "7" -> {
                    barrelTime.text = "$mBeginDate ~ $mEndDate"
                    getViewModel().mUncheckTimeList[6].isChecked = true
                }
                else -> {
                    mBeginDate = getTodayDate()
                    mEndDate = getTodayDate()

                    barrelTime.text = "今日"
                    getViewModel().mUncheckTimeList[0].isChecked = true
                }
            }

            barrelEdit.isGone = intent.getExtra("mode") == "hide"

            barrelTypeLl.oneClick {
                if (mBrandList.isEmpty()) {
                    getBrandList { showBarrelDrop() }
                } else showBarrelDrop()
            }

            barrelTimeLl.oneClick {
                getViewModel()
                    .showDropTimeFilter(
                        getIContext(),
                        barrelTime,
                        barrelTimeArrow,
                        barrelTop,
                        getViewModel().mUncheckTimeList
                    ) { bean ->

                        if (bean.id != "7")
                            getViewModel()
                                .mUncheckTimeList
                                .last()
                                .name = "自定义时间"

                        when (bean.id) {
                            "1" -> {
                                mBeginDate = getTodayDate()
                                mEndDate = getTodayDate()

                                updateList()
                            }
                            "2" -> {
                                mBeginDate = getBeforeDate()
                                mEndDate = getBeforeDate()

                                updateList()
                            }
                            "3" -> {
                                mBeginDate = getMondayDate()
                                mEndDate = getSundayDate()

                                updateList()
                            }
                            "4" -> {
                                mBeginDate = getFirstDate()
                                mEndDate = getEndDate()

                                updateList()
                            }
                            "5" -> {
                                mBeginDate = getBeforeFirstDate()
                                mEndDate = getBeforeEndDate()

                                updateList()
                            }
                            "6" -> {
                                mBeginDate = getYearFirstDate()
                                mEndDate = getYearEndDate()

                                updateList()
                            }
                            "7" -> {
                                showTimeRangeDialog(
                                    isCurrentDate = true,
                                    isAfterLimited = true,
                                    onResult = { start, end ->
                                        getViewModel()
                                            .mUncheckTimeList
                                            .forEach { it.isChecked = false }

                                        getViewModel()
                                            .mUncheckTimeList
                                            .last()
                                            .isChecked = true

                                        mBeginDate = start
                                        mEndDate = end
                                        bean.name = "$mBeginDate ~ $mEndDate"
                                        barrelTime.text = bean.name

                                        updateList()
                                    }
                                )
                            }
                        }
                    }
            }

            barrelEdit.oneClick {
                if (mBarrelId.isEmpty()) {
                    showToast("请先筛选要修改的桶品牌或系列")
                    return@oneClick
                }

                showMemoDialog(
                    title = "修改欠桶",
                    hint = "请输入要修改的桶数",
                    inputType = "number"
                ) { value ->
                    getViewModel()
                        .request(
                            requestUrl = ReportUrl.getBaseUrl().rptStaUpeB,
                            params = arrayOf(
                                "enterpriseId" to intent.getExtra("shopId"),
                                "barrelId" to mBarrelId,
                                "borrow" to value
                            ),
                            onSuccess = {
                                showToast("欠桶修改成功！")

                                // 刷新水站统计列表
                                LiveEventBus
                                    .get("driverStation")
                                    .post("refresh")

                                mBinding.barrelTotal.text = value
                            }
                        )
                }
            }

            barrelRecord.oneClick {
                if (mBarrelId.isEmpty()) {
                    showToast("请先筛选要查看的桶品牌或系列")
                    return@oneClick
                }

                startActivityEx<DriverBarrelRecordActivity>(
                    "shopId" to intent.getExtra("shopId"),
                    "barrelId" to mBarrelId
                )
            }
        }

    }

    /**
     * 品牌筛选
     */
    private fun showBarrelDrop() {
        mBinding.apply {
            getViewModel()
                .showDropTimeFilter(
                    getIContext(),
                    barrelType,
                    barrelTypeArrow,
                    barrelTop,
                    mBrandList
                ) {
                    if (it.id.isEmpty()) {
                        barrelType.setTextColor(getColorEx(R.color.black))
                        barrelTypeArrow.setImageResource(R.mipmap.icon_member01)
                    } else {
                        barrelType.setTextColor(getColorEx(R.color.colorAccent))
                        barrelTypeArrow.setImageResource(R.mipmap.icon_member02)
                    }

                    mBarrelId = it.id

                    updateList()
                }
        }
    }

    /**
     * 桶品牌系列列表
     */
    private fun getBrandList(onFinish: () -> Unit) {
        getViewModel()
            .requestCommon(
                isLoading = true,
                requestUrl = ReportUrl.getBaseUrl().rptStaBrand,
                requestMethod = HttpMethod.GET,
                params = arrayOf(
                    "enterpriseId" to intent.getExtra("shopId")
                ),
                onSuccess = { list ->
                    mBrandList.clear()
                    mBrandList += FilterData("全部", "", "品牌", true)
                    list.mapTo(mBrandList) {
                        FilterData(
                            it.name.orEmpty(),
                            it.id,
                            it.name.orEmpty()
                        )
                    }

                    onFinish.invoke()
                }
            )
    }

    /**
     * 水站回桶记录列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .barrelList(
                page = index,
                type = "",
                shopId = intent.getExtra("shopId"),
                barrelId = mBarrelId,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it.data)
                        it.data.notEmpty { pageNum++ }
                    }

                    mBinding.barrelTotal.text =
                        it.summary?.subQuantity.orEmpty("0")

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}